package com.example.api.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.api.entity.Course;
import com.example.api.entity.CourseOrder;
import com.example.api.entity.User;
import com.example.api.exception.CustomException;
import com.example.api.service.ICourseOrderService;
import com.example.api.service.ICourseService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

import static com.example.api.dto.ResStatusCode.COURSE_ORDER_QUERY_ERROR;
import static com.example.api.dto.ResStatusCode.COURSE_QUERY_ERROR;

/**
 * <p>
 * 订单表 前端控制器
 * </p>
 *
 */
@RestController
@RequestMapping("/api/course-order")
public class CourseOrderController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(CourseOrderController.class);

    @Autowired
    private ICourseService courseService;
    @Autowired
    private ICourseOrderService orderService;


    @PostMapping("/{courseId}")
    @ApiOperation("课程购买接口")
    @PreAuthorize("hasAuthority('ROLE_USER')")
    public ResponseEntity<CourseOrder> buyCourse(
            @PathVariable(value = "courseId",required = true)
                    @ApiParam("课程ID")
            Long courseId
    ) {
        User user =  getUser();
        if (user == null) {
            //用户没登陆
            return ResponseEntity.badRequest().build();
        }

        try {
            //查询课程
            Course course = courseService.getById(courseId);
            if (course != null) {

                CourseOrder order = new CourseOrder();
                order.setCourseId(courseId);
                order.setUserId(user.getId());
                //查询  该用户是否已经购买过
                QueryWrapper<CourseOrder> queryWrapper = new QueryWrapper<>();
                queryWrapper.setEntity(order);
                List<CourseOrder> orders = orderService.list(queryWrapper);
                if (!orders.isEmpty()) {
                    return ResponseEntity.ok(orders.get(0));
                }
                //下单
                order.setCourseTiltle(course.getTitle());
                order.setCreateTime(LocalDateTime.now());
                order.setOrderStatus(2);
                order.setOrderTime(LocalDateTime.now());
                order.setPayPrice(course.getPrice());
                order.setPayTime(LocalDateTime.now());
                orderService.save(order);

                //更新课程的购买人数
                courseService.updateSaleCount(courseId);

                return ResponseEntity.ok(order);
            } else {
                throw new CustomException(courseId+"", COURSE_QUERY_ERROR.getCode(), COURSE_QUERY_ERROR.getMessage());
            }
        } catch (CustomException e) {
            log.error(e.getMessage(),e);
            throw new CustomException(courseId + "", COURSE_ORDER_QUERY_ERROR.getCode(), COURSE_ORDER_QUERY_ERROR.getMessage());
        }
    }
}
